﻿$(document).ready(function () {
    var sequenceNr = 0;
    var sequenceTime = 0;
    var sequenceMissed = 0;
    var sequenceMax = 120; // Number of values to show
    var patId = 1;

    // arrays containing the data
    var dataPulseArray = [];
    var dataOxygenArray = [];

    // add pulse and oxygen data to the array
    function addData(dataPulse, dataOxygen) {
        dataPulseArray.push({ x: sequenceTime, y: dataPulse });
        dataOxygenArray.push({ x: sequenceTime, y: dataOxygen });
        // remove values if over the max size
        if (dataPulseArray.length >= sequenceMax) {
            dataPulseArray.shift();
            dataOxygenArray.shift();
        }
        sequenceTime += 1000;
    }

    function PulseChartInit(seriesPulse, seriesOxygen, resp) {
        seriesPulse.pointStart = new Date(resp[0].time);
        seriesOxygen.pointStart = new Date(resp[0].time);
        sequenceTime = (new Date(resp[0].time)).getTime() - ((sequenceMax - resp.length) * 1000);

        // Add empty values at start if needed
        i = resp.length;
        while (i++ < sequenceMax) {
            addData(null, null);
        }
    }

    function PulseChartAdd(seriesPulse, seriesOxygen, response) {
        for (i = 0; i < response.length; i++) {
            responseTime = (new Date(response[i].time)).getTime();
            // Add empty points if missing values
            while (sequenceTime < responseTime) {
                addData(null, null);
            }
            addData(response[i].pulse, response[i].o2);
            sequenceNr = response[i].seqNr + 1;
        }
        // set data to chart and than redraw
        seriesPulse.setData(dataPulseArray);
        seriesOxygen.setData(dataOxygenArray, true);
    }

    Highcharts.setOptions({
        global: {
            useUTC: false
        }
    });

    $('#container').highcharts({
        chart: {
            type: 'line',
            animation: Highcharts.svg, // don't animate in old IE
            marginRight: 35,
            zoomType: 'xy',
            events: {
                load: function () {
                    // set up the updating of the chart each second
                    var seriesPulse = this.series[0];
                    var seriesOxygen = this.series[1];
                    setInterval(function () {
                        //console.log("Sending Request");
                        $.ajax({
                            url: "dbconnector.php",
                            type: "GET",
                            data: { seqNr: sequenceNr, patId: patId, sequenceMissed: sequenceMissed, sequenceMax: sequenceMax },
                            dataType: "json",
                            timeout: 950
                        }).done(function (response) {

                            if (response.length > 0) {
                                // Init chart on first response
                                if (sequenceNr == 0) {
                                    PulseChartInit(seriesPulse, seriesOxygen, response);
                                }
                                PulseChartAdd(seriesPulse, seriesOxygen, response);
                                sequenceMissed = 0;
                            } else {
                                // Empty JSON data
                                sequenceMissed++;
                                console.log("Empty data");
                            }

                        }).fail(function () {
                            // sequenceMissed++ if error getting the jsondata
                            sequenceMissed++;
                            console.log("Error in request");
                        });
                    }, 1000);
                }
            }
        },
        title: {
            text: 'Live data'
        },
        xAxis: {
            type: 'datetime'
        },
        yAxis: [{
            title: {
                text: null
            },
            labels: {
                formatter: function () {
                    return this.value;
                },
                style: {
                    color: '#666666'
                }
            }
        }],
        tooltip: {
            formatter: function () {
                return '<b>' + this.series.name + '</b><br/>' +
                Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
                this.y;
            }
        },
        legend: {
            enabled: true
        },
        exporting: {
            enabled: false
        },
        series: [{
            name: 'Pulse',
            data: [],
            color: '#ee0000'
        }, {
            name: 'Oxygen',
            data: [],
            color: '#3232cc'
        }],
        plotOptions: {
            line: {
                lineWidth: 2,
                states: {
                    hover: {
                        lineWidth: 3
                    }
                },
                marker: {
                    enabled: false
                },
                pointInterval: 1000
            }
        }
    });
});